#include "testwindow.h"
#include "Debug\ui_testwindow.h"
#include <QGraphicsSimpleTextItem>
#include <time.h>
#include <stdlib.h>
#include <QSizeF>
#include <QMessageBox>

testwindow::testwindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::testwindow)
{
        ui->setupUi(this);
        scene = new QGraphicsScene(QRectF(0,0,800,800));
        grid = new Grid(QPointF(150,150),QPointF(760,530),5,scene->sceneRect(),10);
		scene->addRect(scene->sceneRect());
		ui->gvView->setScene(scene);
		drawNet();
}

void testwindow::drawNet(){
			QGraphicsSimpleTextItem *txt;

        srand(time(NULL));
        int objcount=rand() % 15 + 3;
        for (int i=0;i<objcount;i++)
        {
            QPointF pp( rand() % 600, rand() % 600 );
            QSizeF  sz( rand() % 100 + 50, rand() % 100 + 50);
            addRect(QRectF(pp,sz));
        }

    grid->build();

	scene->addEllipse(QRectF(*(grid->g_goal)-QPointF(6,6),*(grid->g_goal)+QPointF(6,6)),QPen(Qt::red),QBrush(Qt::red,Qt::SolidPattern));
	scene->addEllipse(QRectF(*(grid->g_start)-QPointF(6,6),*(grid->g_start)+QPointF(6,6)),QPen(Qt::blue),QBrush(Qt::blue,Qt::SolidPattern));
	
	scene->addEllipse(QRectF(grid->goal-QPointF(4,4),grid->goal+QPointF(4,4)),QPen(Qt::yellow),QBrush(Qt::yellow,Qt::SolidPattern));
	scene->addEllipse(QRectF(grid->start-QPointF(4,4),grid->start+QPointF(4,4)),QPen(Qt::yellow),QBrush(Qt::yellow,Qt::SolidPattern));

	txt = scene->addSimpleText(QString("Goal"));
	txt->setPos(grid->goal-QPointF(-10,12));
	txt = scene->addSimpleText(QString("Start"));
	txt->setPos(grid->start-QPointF(-10,12));
	
	for (int i = 0; i < grid->gridHLines.size(); i++){
		for (int j = 0; j < grid->gridVLines.size(); j++){
			if (grid->gridPoints[i][j]->neighborsCount())
				scene->addEllipse(QRectF(*(grid->gridPoints[i][j])-QPointF(1.2,1.2),*(grid->gridPoints[i][j])+QPointF(1.2,1.2)),QPen(Qt::black),QBrush(Qt::black,Qt::SolidPattern));
			for (int k = 0; k < grid->gridPoints[i][j]->neighborsCount(); k++){
				scene->addLine(QLineF(*(grid->gridPoints[i][j]),*((*(grid->gridPoints[i][j]))[k]) ),QPen(QBrush(Qt::blue,Qt::SolidPattern),0.5));
			}
		}
	}

    QVector<QPointF> path=grid->getPath();
    if (path.size()==0) {
        QMessageBox::critical(NULL,"Path not found","Path not found");
    }
    for (int i=1;i<path.size();i++) {
        scene->addLine(QLineF(path[i-1],path[i]),QPen(QBrush(Qt::red),2.0));
    }
	
}
testwindow::~testwindow()
{
    delete ui;
}
